package com.alquimia.identityaccess.domain.model;

import java.io.Serializable;
import java.util.regex.Pattern;

/**
 * Created by Ivo on 12/07/2014.
 */
public final class EmailAddress implements Serializable {

    private static final long serialVersionUID = 1L;
    private String address;

    public EmailAddress(String aAddress) {

        this();
        setAddress(aAddress);
    }

    public EmailAddress(EmailAddress aEmailAddress) {
        this(aEmailAddress.address());
    }

    @Override
    public boolean equals(Object anObject) {
        boolean equalObjects = false;

        if (anObject != null && this.getClass() == anObject.getClass()) {
            EmailAddress typedObject = (EmailAddress) anObject;
            equalObjects = this.address().equals(typedObject.address());
        }

        return equalObjects;
    }

    @Override
    public int hashCode() {
        int hashCodeValue =
                +(17861 * 179)
                        + this.address().hashCode();

        return hashCodeValue;
    }

    @Override
    public String toString() {
        return "EmailAddress [address=" + address + "]";
    }

    protected EmailAddress() {
        super();
    }

    public String address() {
        return this.address;
    }

    private void setAddress(final String aAddress) {

        if (aAddress.isEmpty())
            throw new NullPointerException("La dirección no puede ser nula.");

        if (!Pattern.matches("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*", aAddress))
            throw new IllegalArgumentException("El emailAddress debe tener un formato válido.");

        this.address = aAddress;
    }

}
